package com.qzq.weibo.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.qzq.weibo.R;
import com.qzq.weibo.http.HttpRequest;
import com.qzq.weibo.utils.Utils;
import com.qzq.weibo.view.LoadingDialog;

public class PublishActivity extends Activity implements OnClickListener,
		TextWatcher {

	private Button btn_publish;
	private Button btn_cancel;
	private EditText et_content;

	private ImageView iv_delete;
	private ImageView iv_emotion;
	private ImageView iv_photo;
	private ImageView iv_camera;

	private TextView tv_text_num_left;

	private ImageView iv_image;

	private String status;
	private File file;

	private int nor_color;
	private int warning_color;

	private Utils utils;
	private HttpRequest http;

	private LoadingDialog loading;

	private static final String TAG = "PublishActivity";
	private static final int IMAGE_CODE = 1;
	private static final int CAMERA_CODE = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_publish);

		initView();
		initMember();
	}

	/**
	 * 初始化页面布局
	 * 
	 */
	private void initView() {
		btn_cancel = (Button) this.findViewById(R.id.publish_bar_btn_cancel);
		btn_publish = (Button) this.findViewById(R.id.publish_bar_btn_publish);
		et_content = (EditText) this.findViewById(R.id.publish_et_content);

		iv_delete = (ImageView) this.findViewById(R.id.publish_iv_delete);
		iv_emotion = (ImageView) this.findViewById(R.id.publish_iv_emotion);
		iv_photo = (ImageView) this.findViewById(R.id.publish_iv_photo);
		iv_camera = (ImageView) this.findViewById(R.id.publish_iv_camera);

		iv_image = (ImageView) this
				.findViewById(R.id.publish_iv_selected_image);

		tv_text_num_left = (TextView) this
				.findViewById(R.id.publish_tv_text_num_left);
	}

	/**
	 * 初始化成员变量
	 * 
	 */
	private void initMember() {
		http = HttpRequest.getInstance(getApplicationContext());
		utils = Utils.getInstance(getApplicationContext());

		file = null;

		nor_color = getResources().getColor(R.color.black);
		warning_color = getResources().getColor(R.color.red_lite);

		btn_cancel.setOnClickListener(this);
		btn_publish.setOnClickListener(this);
		et_content.addTextChangedListener(this);

		iv_emotion.setOnClickListener(this);
		iv_delete.setOnClickListener(this);
		iv_photo.setOnClickListener(this);
		iv_camera.setOnClickListener(this);
	}

	/**
	 * 发布文字微博的实现
	 * 
	 */
	@SuppressLint("HandlerLeak")
	private void publishTextStatus(String status) {
		if (status.length() > 0) {
			if (status.length() <= 140) {
				loading = new LoadingDialog(PublishActivity.this,
						R.style.Theme_Transparent, "上传中，请稍后...");
				loading.show();
				http.requestPublishTextStatus(new Handler() {

					@Override
					public void handleMessage(Message msg) {
						if (msg != null) {
							int flag = msg.what;
							loading.dismiss();
							if (flag == HttpRequest.REQUEST_FAILER) {
								HttpRequest.badRequest(
										Integer.parseInt(msg.obj.toString()),
										getApplicationContext());
							} else {
								utils.setToastMsg("发布成功");
								finish();
							}
						}
						super.handleMessage(msg);
					}

				}, status);
			} else {
				utils.setToastMsg("超过字数限制");
			}
		} else {
			utils.setToastMsg("内容不能为空");
		}
	}

	@SuppressLint("HandlerLeak")
	private void publishImageStatus(String status) {
		if (status.equals("")) {
			utils.setToastMsg("微博内容不能为空!");
		} else {

			loading = new LoadingDialog(PublishActivity.this,
					R.style.Theme_Transparent, "上传中，请稍后...");
			loading.show();
			http.requestPublishImageStatus(new Handler() {

				@Override
				public void handleMessage(Message msg) {
					if (msg != null) {
						int flag = msg.what;
						loading.dismiss();
						if (flag == HttpRequest.REQUEST_FAILER) {
							HttpRequest.badRequest(
									Integer.parseInt(msg.obj.toString()),
									getApplicationContext());
						} else {
							utils.setToastMsg("发布成功");
							finish();
						}
					}
					super.handleMessage(msg);
				}

			}, status, file);
		}
	}

	/**
	 * 发布微博的点击事件
	 */
	private void onClickPublish() {
		if (et_content.length() > 140) {
			utils.setToastMsg("超出字数限制");
		} else if (file == null) {
			status = et_content.getText().toString();
			publishTextStatus(status);
		} else {
			status = et_content.getText().toString();
			publishImageStatus(status);
		}
	}

	/**
	 * 从图库中选择图片
	 * 
	 */
	private void onClickAddPhoto() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("image/*");
		startActivityForResult(intent, IMAGE_CODE);

	}

	/**
	 * 调用系统相机拍照
	 * 
	 */
	private void onClickCamera() {

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, CAMERA_CODE);
	}

	/**
	 * 获取相册返回的相片 || 获得相机拍摄的相片
	 * 
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK) {
			Log.d(TAG, "ActivityResult resultCode error");
			return;
		}

		/** 调用系统相册返回结果 */
		if (requestCode == IMAGE_CODE && data != null) {

			Uri selectedImage = data.getData();
			String[] filePathColumns = { MediaStore.Images.Media.DATA };
			Cursor c = this.getContentResolver().query(selectedImage,
					filePathColumns, null, null, null);
			c.moveToFirst();

			int columnIndex = c.getColumnIndex(filePathColumns[0]);
			String picturePath = c.getString(columnIndex);

			file = new File(picturePath);

			iv_image.setImageBitmap(BitmapFactory.decodeFile(picturePath));
			iv_image.setVisibility(View.VISIBLE);

			Log.d(TAG, picturePath);
			c.close();

			/** 调用相机返回的结果 */
		} else if (requestCode == CAMERA_CODE && data != null) {

			Bundle extras = data.getExtras();
			Bitmap bm = (Bitmap) extras.get("data");
			iv_image.setImageBitmap(bm);
			iv_image.setVisibility(View.VISIBLE);
			file = bitmap2File(bm);
		}
	}

	/**
	 * 所有的按钮事件
	 * 
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.publish_bar_btn_cancel:
			finish();
			break;

		case R.id.publish_bar_btn_publish:
			onClickPublish();
			break;

		case R.id.publish_iv_emotion:

			break;

		case R.id.publish_iv_delete:
			et_content.setText("");
			break;

		case R.id.publish_iv_photo:
			onClickAddPhoto();
			break;

		case R.id.publish_iv_camera:
			onClickCamera();
			break;
		default:
			break;
		}
	}

	/**
	 * 将相机返回的bitmap写到sdcard上
	 * 
	 * @param bm
	 * @return
	 */
	private File bitmap2File(Bitmap bm) {
		File file = new File("//mnt/sdcard/temp.jpg");
		BufferedOutputStream bos;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(file));
			bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}

	/**
	 * EditText的输入字符动态获取
	 */

	@Override
	public void afterTextChanged(Editable s) {

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (et_content.getText().length() <= 140) {

			tv_text_num_left.setTextColor(nor_color);
			tv_text_num_left.setText(String.valueOf((140 - et_content.getText()
					.length())));
		} else {
			tv_text_num_left.setTextColor(warning_color);
			tv_text_num_left.setText("超出"
					+ String.valueOf((et_content.getText().length() - 140)));
		}
	}

}
